package io.tec.cloud.algorithm;

/**
 * https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
 * 121. 买卖股票的最佳时机
 * <p>
 * 给定一个数组 prices ，它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
 * <p>
 * 你只能选择 某一天 买入这只股票，并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
 * <p>
 * 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润，返回 0 。
 * <p>
 * <p>
 * 1 <= prices.length <= 10^5
 * 0 <= prices[i] <= 10^4
 */
public class P121_best_time_to_buy_and_sell_stock {
    public int maxProfit(int[] prices) {
        int p = 0;
        for (int i = prices.length - 1; i >= 1; i--) {
            int sell = prices[i];
            int buy = prices[i - 1];
            for (int j = i - 1; j >= 0; j--) {
                buy = Math.min(buy, prices[j]);
            }
            p = (sell - buy > 0) ? Math.max(p, sell - buy) : p;
        }
        return p;
    }


    public int maxProfit2(int[] prices) {
        int min = prices[prices.length - 1];
        int[] minArray = new int[prices.length];
        for (int i = prices.length - 1; i >= 0; i--) {
            if (min > prices[i]) {
                min = prices[i];
            }
            minArray[i] = Math.min(min, prices[i]);
        }
        for (int i = minArray.length - 1; i >= 0; i--) {
            min = Math.min(min, minArray[i]);
        }
        int p = 0;
        for (int i = prices.length - 1; i >= 0; i--) {
            p = Math.max(p, prices[i] - min);
        }
        return p;
    }

    public int maxProfit3_1(int[] prices) {
        int min = prices[0];
        int[] minArray = new int[prices.length];
        for (int i = 0; i < prices.length; i++) {
            if (min > prices[i]) {
                min = prices[i];
            }
            minArray[i] = min;
        }
        int p = 0;
        for (int i = 0; i < prices.length; i++) {
            p = Math.max(prices[i] - minArray[i], p);
        }
        return p;
    }

    public static int maxProfit3_2(int[] prices) {
        int min = prices[0];
        int p = 0;
        for (int i = 0; i < prices.length; i++) {
            min = Math.min(prices[i], min);
            p = Math.max(prices[i] - min, p);
        }
        return p;
    }

    public static int dp(int[] prices) {
        int min = prices[0];
        int p = 0;
        int[] dp = new int[prices.length];
        for (int i = 1; i < prices.length; i++) {
            min = Math.min(prices[i], min);
            dp[i] = Math.max(dp[i - 1], prices[i] - min);
        }
        return dp[dp.length - 1];
    }

    public static void main(String[] args) {
        int[] array = new int[]{7, 1, 5, 3, 6, 4};
        maxProfit3_2(array);
    }
}
